/* eslint-disable */
'use strict'

const express = require('express')
const router = express.Router()
const log4js = require('log4js')
const logger = log4js.getLogger('addConsumer')
const dbconnection = require('../config/database.js')

const checkConsumer = (name, birthday, flag, callback) => {
  dbconnection.execute('SELECT * FROM infos WHERE name = ? and birthday = ? and flag = ?', [name, birthday, flag], callback)
}
const checkConsumerPromise = (name, birthday, flag) => new Promise((resolve, reject) => {
  checkConsumer(name, birthday, flag, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})
const insertConsumer = (consumer, callback) => {
  dbconnection.execute('INSERT INTO infos SET ?', consumer, callback)
}
const insertConsumerPromise = consumer => new Promise((resolve, reject) => {
  insertConsumer(consumer, (err, results, fields) => {
    if (err) {
      logger.error(err)
      reject(err)
    } else {
      resolve(results)
    }
  })
})

router.post('/consumer', (req, res, next) => {
  if (req.session.uuid !== req.cookies.uuid || !req.session.uuid) {
    logger.error(req.session.uuid, req.cookies.uuid)
    return res.send({rtnCode:'302', rtnMsg: '登录过期，请重新登录'});
  }
  let consumer = {
    name: req.body.name,
    mobile: req.body.mobile,
    left: req.body.left,
    right: req.body.right,
    birthday: req.body.birthday,
    flag: req.session.flag
  }
  logger.debug('flag' + consumer.flag)
  checkConsumerPromise(consumer.name, consumer.birthday, consumer.flag).then(results => {
    if (results.length > 0) {//已经添加过
      res.send({rtnCode: '400', rtnMsg: '请勿重复添加顾客资料'})
    } else {
      insertConsumer(consumer, (err, results, fields) => {
        if (err) {
          logger.error(err)
          res.status(500).send({rtnCode: '500', rtnMsg: '服务器错误'})
          throw err
        }
        res.send({rtnCode: '000', rtnMsg: '成功添加顾客资料'})
      })
    }
  }).catch(err => {
    logger.error(err)
    res.send({rtnCode: '500', rtnMsg: '网络问题，请稍后重试'})
  })
  
})

module.exports = router
